using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Work.API.Applications.Read.Commands;
using Work.API.Dtos;
using Work.ErrorCode;
using Work.Infrastructure.Interfaces;

namespace Work.API.Applications.Read.CommandHandlers
{
    /// <summary>
    /// 根据预约ID获取处方明细处理器
    /// </summary>
    public class GetPrescriptionItemsByAppointmentQueryHandler : IRequestHandler<GetPrescriptionItemsByAppointmentQuery, ApiResult<List<PrescriptionItemDto>>>
    {
        private readonly IBaseRepository<Domain.PrescriptionItem> _prescriptionItemRepo;
        private readonly IMapper _mapper;

        public GetPrescriptionItemsByAppointmentQueryHandler(
            IBaseRepository<Domain.PrescriptionItem> prescriptionItemRepo,
            IMapper mapper)
        {
            _prescriptionItemRepo = prescriptionItemRepo;
            _mapper = mapper;
        }

        public async Task<ApiResult<List<PrescriptionItemDto>>> Handle(GetPrescriptionItemsByAppointmentQuery request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<List<PrescriptionItemDto>>();

            try
            {
                var query = _prescriptionItemRepo.GetAll()
                    .Where(x => x.AppointmentId == request.AppointmentId);

                // 如果只查询未支付的
                if (request.UnpaidOnly == true)
                {
                    query = query.Where(x => x.PaymentStatus == "未支付");
                }

                var prescriptionItems = await query
                    .OrderByDescending(x => x.CreateTime)
                    .ToListAsync(cancellationToken);

                result.Code = ApiEnum.成功;
                result.Message = "查询成功";
                result.Data = _mapper.Map<List<PrescriptionItemDto>>(prescriptionItems);
            }
            catch (System.Exception ex)
            {
                result.Code = ApiEnum.失败;
                result.Message = $"查询失败：{ex.Message}";
                result.Data = new List<PrescriptionItemDto>();
            }

            return result;
        }
    }
}

